package com.xian.interceptor;

import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

/**
 * 自定义一个在消息前打印当前时间拦截器
 */
public class TimeInterceptor implements ProducerInterceptor<String,String> {

    //在发送前搞搞事，嘻嘻
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) {

        String time = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS")).toString();
        String result = time + record.value();


        // 创建一个新的record，把时间戳写入消息体的最前部  把record所有信息设置回去，就修改value
        return new ProducerRecord(record.topic(), record.partition(), record.timestamp(), record.key(), result);




    }

    @Override
    public void onAcknowledgement(RecordMetadata metadata, Exception exception) {

    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
